package com.gwsoft.mm.file;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;


public class FileHandlerServlet extends DispatcherServlet {
	private static final long serialVersionUID = 1L;
	private FileHandlerManage fsManage;

	public void init() throws ServletException {
		ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
		fsManage = (FileHandlerManage) ctx.getBean("fileHandlerManage");		
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);

		if (isMultipart) {
			multipart(request, response);
		} else {
			notMultipart(request, response);
		}

	}

	private void notMultipart(HttpServletRequest request, HttpServletResponse response) {
		ServiceProperties properties = super.beginExecute(request);
		getUserInfo(properties, request);
		if (properties.containsKey("METHOD")) {
			String method = properties.getString("METHOD");
			Object returnJson = this.dispatch(method, fsManage, properties);
			JSONObject json = (JSONObject) returnJson;
			if (!json.containsKey("error") && json.containsKey("filepath")) {
				try {
					pushFile(json.getString("filepath"), response);					
				} catch (Exception e) {
					json.put("error", "下载文件出错");
					e.printStackTrace();
				}
			}
			if (json.containsKey("filePath")) {
				FileUpLoad.deleteFile(json.getString("filepath"));
				json.clear();
			}	
			super.endExecute(response, json);
		}
	}

	private void multipart(HttpServletRequest request, HttpServletResponse response) {
		//upload file part
		FileUpLoad2 upload = new FileUpLoad2(request, response);
		upload.setChangeFileName(false);
		upload.init();
		
		ServiceProperties properties = upload.getProperties();
		getUserInfo(properties, request);
		Object returnJson = null;
		
		returnJson = this.dispatch(properties.getString("METHOD"), fsManage, properties);
		JSONObject result = (JSONObject) returnJson;
		
		if (result.containsKey("filepath")) {
			FileUpLoad.deleteFile(result.getString("filepath"));
			result.remove("filepath");
		}
		synchronized (this) {
			if (result.containsKey("error")) {
				upload.setStatus(FileUpLoad2.UPLOAD_STATUS_ERROR);
				upload.setErrorMessage(result.getString("error"));
			} else {
				upload.setStatus(FileUpLoad2.UPLOAD_STATUS_NORMAL);
				upload.setErrorMessage("上传成功，"+result.getString("rowcount"));
			}
		}
		upload.writeToClient();
	}
	
	private synchronized ServiceProperties getUserInfo(ServiceProperties properties, HttpServletRequest request) {

		User user = (User) request.getSession().getAttribute("loginUser");
		if (user != null) {
			properties.addProperty("OPERATORNAME", user.getLoginName());
			properties.addProperty("OPERATORID", String.valueOf(user.getOperatorId()));
			//			properties.addProperty("SPCODE", String.valueOf(user.getSpcode()));
		} else {
			properties.addProperty("OPERATORID", "1");
		}
		return properties;
	}
	
	/**
	 * @throws IOException 
	 * @Fun: 下载文件实现
	 */
	private void pushFile(String filePath, HttpServletResponse response) throws IOException {
		System.out.println("Start to push file to client");
		response.reset();
		response.setContentType("application/x-msdownload;charset=UTF-8");		
		response.addHeader("Content-Disposition","attachment;filename=template.xls");
	
		OutputStream out = null;
		FileInputStream in = null;
		
		out = response.getOutputStream();
		in = new FileInputStream(filePath);
		byte[] b = new byte[1024];
		int i = 0;
		
		while((i = in.read(b))!=-1){
			out.write(b, 0, i);	
		}
		out.flush();
		if(in != null){
			in.close();
			out.close();
		}
	}
}